<script type="text/ecmascript-6">
    /**
     * Created by wcz on 2017/1/7.
     */
    import 'babel-polyfill'
    import b from '../bus'

    export default {
        data () {
            return {
                comments: [],
                pageIndex: 1,
                pageSize: 15,
                total: 0,
                imgVisible: false,
                pointImgSlim: '',
                pointMsg: '',
                searchForm: {
                    state: '3',
                    name: '',
                    car_num: '',
                    city: '',
                    down_role: '',
                    company: ''
                },
                cdn: window.cdn,
                geocoder: null
            }
        },
        created () {
            AMap.service('AMap.Geocoder', () => {
                //实例化Geocoder
                this.geocoder = new AMap.Geocoder({
                    radius: 1000,
                    extensions: "all"
                });
            });
        },
        computed: {
            isListEmpty () {
                return (this.comments.length == 0)
            }
        },
        mounted () {
            this.getList();
        },
        methods: {
            getList (currentPage = 1) {
                let pd = {};
                pd.p = currentPage;
                pd.s = this.pageSize;
                pd.state = this.searchForm.state;
                pd.name = this.searchForm.name;
                pd.car_num = this.searchForm.car_num;
                pd.city = this.searchForm.city;
                pd.company = this.searchForm.company;
                pd.down_role = this.searchForm.down_role;

                if (this.searchForm.state == '3') {
                    pd.match = true
                }

                this.get('/api/v1/traces', pd, {loading: 'xhrPending', errmsg: '获取情报列表失败'})
                    .then(res => {
                        if (res.success && res.data.rows) {
                            this.comments = res.data.rows.map((e, i) => {
                                let ele = e;
                                let photo = e.car_photo || ''
                                ele.isAli = e.car_photo.includes('aixuedaiimg')
                                ele.time = e.create_at.split(' ')[0];
                                ele.location = e.location || '无';
                                ele.fingerprint = e.fingerprint || '未成功获取';
                                if (e.car_photo && ele.isAli) {
                                    ele.car_photo = e.car_photo
                                    ele.car_photo_slim = e.car_photo
                                } else {
                                    ele.car_photo_slim = cdn + e.car_photo + '?imageslim'
                                    ele.car_photo = cdn + photo + '?imageView2/0/w/100'
                                }
                                if (ele.fingerprint != '未成功获取') {
                                    let lnglatXY = ele.fingerprint.split(',').map(e => Number(e).toFixed(6));
                                    this.regeocoder(lnglatXY)
                                        .then(address => {
                                            this.comments[i].fingerprint = address;
                                        });
                                }
                                if (ele.isAli) {
                                    axios.post('/getAliGpsInfo', {
                                        url: photo + '?x-oss-process=image/info'
                                    }).catch(e => {
                                        console.log(e)
                                    }).then(data => {
                                        let res = data.data
                                        this.comments[i].photo_time = res.time
                                        if (res.success) {
                                            return this.regeocoder(res.lnglatXY)
                                        } else {
                                            this.comments[i].photo_city = res.lnglatXY;
                                        }

                                    }).then(address => {
                                        this.comments[i].photo_city = address;
                                    })
                                } else {
                                    axios.get(cdn + photo + '?exif').catch(err => {
                                        console.warn(err)
                                    }).then(data => {
                                        let res = data.data;
                                        let Longitude;
                                        let Latitude;
                                        if (res.DateTimeOriginal) {
                                            this.comments[i].photo_time = res.DateTimeOriginal.val;
                                        }

                                        if (res.GPSLongitude) {
                                            Longitude = this.transformTude(res.GPSLongitude.val);
                                            Latitude = this.transformTude(res.GPSLatitude.val);
                                            return [Longitude, Latitude]
                                        } else {
                                            this.comments[i].photo_city = '未成功获取';
                                            return Promise.reject('')
                                        }

                                    }).then(lnglatXY => {
                                        return this.regeocoder(lnglatXY)
                                    }).then(address => {
                                        this.comments[i].photo_city = address;
                                    });
                                }


                                return ele
                            });

                            this.pageIndex = res.data.page + 1;
                            this.total = res.data.total;
                        } else {
                            this.comments = [];
                        }
                    })
            },

            handleTabSelect (state) {
                this.searchForm.state = state;
                this.getList();
            },
            changeIndex (p) {
                this.getList(p)
            },
            viewImg (imgSrc, msg) {
                this.pointImgSlim = imgSrc;
                this.pointMsg = msg;
                this.imgVisible = true;
            },
            closeView () {
                this.imgVisible = false;
                this.pointImgSlim = ''
            },
            search () {
                if (this.searchForm.down_role != 1) {
                    this.searchForm.company = ''
                }
                this.getList()
            },
            pass (id) {
                this.$confirm('确认情报有效，请慎重？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let postData = new FormData();
                    postData.append('verify', 1);

                    this.jax(`/api/v1/traces/${id}/verify`, postData, {errmsg: '请求失败，请稍后再试'})
                        .then(res => {
                            if (res.success) {
                                this.msg('成功通过', 'success');
                                this.getList();
                                b.$emit('resCount');
                            }
                        })
                }).catch(() => {
                })


            },
            del (id) {
                this.$confirm('确认扔进垃圾池吗，请慎重？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let postData = new FormData();
                    postData.append('state', 5);

                    this.jax(`/api/v1/traces/${id}/state`, postData, {errmsg: '请求失败，请稍后再试'})
                        .then(res => {
                            if (res.success) {
                                this.msg('成功扔进垃圾池', 'success');
                                this.getList();
                                b.$emit('resCount');
                            }
                        })
                }).catch(() => {
                })
            },
            refuse (id) {
                this.$confirm('确认删除情报吗，请慎重？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let postData = new FormData();
                    postData.append('verify', 0);

                    this.jax(`/api/v1/traces/${id}/verify`, postData, {errmsg: '请求失败，请稍后再试'})
                        .then(res => {
                            if (res.success) {
                                this.msg('成功拒绝', 'success');
                                this.getList();
                                b.$emit('resCount');
                            }
                        })
                }).catch(() => {
                })
            },
            regeocoder (lnglatXY) {
                let self = this;
                return new Promise((resolve, reject) => {
                    this.geocoder.getAddress(lnglatXY, (status, result) => {
                        if (status === 'complete' && result.info === 'OK') {
                            resolve(self.geocoder_CallBack(result))
                        } else {
                            console.log('获取地理位置失败');
                        }
                    });
                })
            },
            geocoder_CallBack(data) {
                return data.regeocode.formattedAddress; //返回地址描述
            },
            transformTude (tude) {
                let rst = tude.split(', ').map(e => Number(e));
                return (rst[0] + rst[1] / 60 + rst[2] / 3600).toFixed(6)
            },
            transformAli (tude) {
                let arr = /(\d+)deg\s(\d+)\'\s(\d+.\d+)\"/.exec(tude)
                return arr[1] + ', ' + arr[2] + ', ' + arr[3]
            }
        },
    };
</script>

<template>
  <div class="comments">
    <el-menu default-active="3" mode="horizontal" @select="handleTabSelect" layout="row center-left">
      <el-menu-item index="3">待审查</el-menu-item>
      <el-menu-item index="1">有效情报</el-menu-item>
      <el-menu-item index="2">已完成</el-menu-item>
      <el-menu-item index="0">库存</el-menu-item>
      <el-menu-item index="0,1,2,3">所有</el-menu-item>
      <div self="right" class="cb__bar-right cb__bar-right--800" layout="row center-justify">
        <el-input
                class="tasks__tool-input tasks__tool-input--small"
                placeholder="按线人名字搜索"
                icon="search"
                @change="search"
                v-model="searchForm.name">
        </el-input>
        <el-input
                class="tasks__tool-input tasks__tool-input--small"
                placeholder="按市搜索"
                icon="search"
                @change="search"
                v-model="searchForm.city">
        </el-input>
        <el-input
                v-if="searchForm.down_role == 1"
                class="tasks__tool-input tasks__tool-input--small"
                placeholder="按公司搜索"
                icon="search"
                @change="search"
                v-model="searchForm.company">
        </el-input>
        <el-select class="tasks__tool-input--small" v-model="searchForm.down_role" @change="search"
                   placeholder="按线人类型">
          <el-option label="全部" value=""></el-option>
          <el-option label="A类" value="0"></el-option>
          <el-option label="B类" value="1"></el-option>
          <el-option label="C类" value="2"></el-option>
        </el-select>
        <el-input
                class="tasks__tool-input tasks__tool-input--small"
                placeholder="按车牌搜索"
                icon="search"
                @change="search"
                v-model="searchForm.car_num">
        </el-input>
      </div>
    </el-menu>
    <!-- list-->
    <div class="comments__content">
      <div class="wh-table">
        <div class="wh-table__thead" layout="row center-left">
          <div class="th w10">任务车牌号</div>
          <div class="th w12">查看照片</div>
          <div class="th w10">线人信息</div>
          <div class="th w10">上传时间</div>
          <div class="th w15">GPS定位</div>
          <div class="th w15">照片拍摄地/时间</div>
          <!--<div class="th w12 tac" v-if="searchForm.state == '0'">是否活动</div>-->
          <div class="th w12 tac">描述地址</div>
          <div class="th w10 tac"><i class="el-icon-more"></i></div>
        </div>
        <div v-if="isListEmpty" class="wh-table__tbody--empty">无记录</div>
        <div v-else class="wh-table__tbody" layout="row center-left" v-for="(comment, index) in comments">
          <div class="td w10">
            <h5 class="wh-table__em">{{comment.car_number}}</h5>
          </div>
          <div class="td w12 comments__view" @click="viewImg(comment.car_photo_slim, comment.car_number)">
            <div class="wh-table__thumbnail wh-table__thumbnail--vertical" data-content="点击查看情报照片">
              <img :src="comment.car_photo"
                   class="wh-table__thumbnail-inner">
            </div>
          </div>
          <div class="td w10">
            <p class="wh-table__em">{{comment.name}}</p>
            <p>{{comment.city}}</p>
            <p>{{comment.phone}}</p>
          </div>
          <div class="td w10">
            <el-tooltip placement="top" :content="comment.create_at">
              {{comment.time}}



            </el-tooltip>
          </div>
          <div class="td w15">{{comment.fingerprint}}</div>
          <div class="td w15">
            <p>{{comment.photo_city}}</p>
            <hr>
            <p>{{comment.photo_time}}</p>
          </div>
          <!--<div class="td w12 tac" v-if="searchForm.state == '0'" layout="column center-center">-->
          <!--<i v-if="comment.is_activity" class="iconfont success">&#xe600;</i>-->
          <!--<i v-else class="iconfont error">&#xe84c;</i>-->
          <!--</div>-->
          <div class="td w12 tac">{{comment.location}}</div>
          <div class="td w10" layout="row center-right">
            <el-button type="primary" v-if="comment.state == 3" @click="pass(comment.id)">通过</el-button>
            <el-button type="danger" :plain="true" v-if="comment.state == 0" @click="del(comment.id)">
              扔到垃圾池


            </el-button>
            <el-button type="danger" v-if="comment.state == 3 || comment.state == 1" plain
                       @click="refuse(comment.id)">拒绝



            </el-button>
          </div>
        </div>

        <!-- pagination-->
        <div v-if="!isListEmpty" class="wh-table__page" layout="row center-center">
          <el-pagination
                  @current-change="changeIndex"
                  :current-page="pageIndex"
                  :page-size="pageSize"
                  :total="total"
          >
          </el-pagination>
        </div>
      </div>
    </div>
    <!-- viewImg-->
    <div v-if="imgVisible" class="img__modal" layout="column center-center">
      <i class="img__close el-icon-close" @click="closeView"></i>
      <p class="point__msg">任务车牌号：{{pointMsg}}</p>
      <img :src="pointImgSlim" class="img__big"/>
    </div>
  </div>
</template>